//
//  MainViewController.m
//  Gabber
//
//  Created by 惠国 陆 on 11-11-18.
//  Copyright (c) 2011年 恒生聚源. All rights reserved.
//

#import "MainViewController.h"
#import "XMPPClient.h"
#import "Message.h"
#import "ChatViewController.h"
#import "RosterTitleView.h"


@implementation MainViewController

@synthesize tabBar=_tabBar;
@synthesize tabDict=_tabDict;
@synthesize unreadController = _unreadController;
@synthesize jid = _jid;
@synthesize chatViewController = _chatViewController;
@synthesize toolbar = _toolbar;
@synthesize titleView = _titleView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleMessageReceived:) name: kMessageReceivedNotification object: nil]; 
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleChatSwitch:) name: kChatSwitchNotification object: nil]; 
        
        self.tabDict= [NSMutableDictionary dictionary];
        
        [self updateBadge];
        
        //[[[XMPPClient sharedInstance]xmppStream] addDelegate: self delegateQueue:dispatch_get_main_queue()];
        
        
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    //[[[XMPPClient sharedInstance]xmppStream] removeDelegate:self];
    TT_RELEASE_SAFELY(_tabBar);
    TT_RELEASE_SAFELY(_tabDict);
    TT_RELEASE_SAFELY(_jid);
    
    TT_RELEASE_SAFELY(_unreadController);
    
    
    TT_RELEASE_SAFELY(_chatViewController);
    TT_RELEASE_SAFELY(_toolbar);
    TT_RELEASE_SAFELY(_titleView);
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:self.view.frame];
    backgroundView.image=[UIImage imageNamed:@"Background"];
    backgroundView.contentMode= UIViewContentModeCenter;
    backgroundView.autoresizingMask =UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:backgroundView];
    [backgroundView release];
    
    _tabBar = [[TTTabStrip alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 41)];
    
    _tabBar.delegate = self;
    [self.view addSubview:_tabBar];
    _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, _tabBar.bottom,
                                                           self.view.width, 44)];
    _toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _titleView = [[RosterTitleView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] ;
    UIBarItem* avatarButton = [[[UIBarButtonItem alloc] initWithCustomView:_titleView] autorelease];
    
    UIBarItem* space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                         UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
    UIBarItem* closeButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(closeAction:)] autorelease];
    _toolbar.items = [NSArray arrayWithObjects: avatarButton, space, closeButton, nil];
    
    [self.view addSubview:_toolbar];
    _toolbar.hidden = YES;
    
    self.navigationController.navigationBarHidden = YES;
    
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [super viewWillAppear:animated];
    [[[XMPPClient sharedInstance]xmppStream] addDelegate: self delegateQueue:dispatch_get_main_queue()];   
}

- (void)viewDidAppear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [super viewDidAppear:animated];
    [self fetchUnreadMessages];
}

- (void)viewDidDisappear:(BOOL)animated
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [[[XMPPClient sharedInstance]xmppStream] removeDelegate:self];
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (self.chatViewController.facialPopover && self.chatViewController.facialPopover.popoverVisible){
        [self.chatViewController.facialPopover dismissPopoverAnimated:NO];
    }
   
}

- (NSFetchedResultsController *)unreadController
{
	if (_unreadController == nil)
	{
		NSManagedObjectContext *moc = [[XMPPClient sharedInstance] managedObjectContext_message];
		
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
		                                          inManagedObjectContext:moc];
		NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"jidStr" ascending:YES];
        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO];
        
        
		
        
        NSPredicate *predicate=  [NSPredicate predicateWithFormat:@"streamBareJidStr == %@ AND read == %@ AND outbound == %@ ",
                                  [[[[XMPPClient sharedInstance] xmppStream]myJID] bare],[NSNumber numberWithBool:NO],[NSNumber numberWithBool:NO]];
        
        
        
		NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
		
		NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
		[fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
		[fetchRequest setSortDescriptors:sortDescriptors];
		[fetchRequest setFetchBatchSize:10];
		
		_unreadController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"jidStr" cacheName:nil];
		[_unreadController setDelegate:self];
        //        NSError *error = nil;
        //        if (![[self unreadController] performFetch:&error])
        //        {
        //            DDLogWarn(@"Error performing fetch: %@", error);
        //        }         
        
		[sd1 release];
        [sd2 release];
		[fetchRequest release];
	}
    return _unreadController;
}

- (void)fetchUnreadMessages
{
    TT_RELEASE_SAFELY(_unreadController);
    
    NSError *error = nil;
    if (![self.unreadController performFetch:&error])
    {
        DDLogWarn(@"Error performing fetch: %@", error);
    }    
    for (id <NSFetchedResultsSectionInfo> sectionInfo in [self.unreadController sections]) {
        
        NSString* jidStr= sectionInfo.name;
        XMPPJID* jid = [XMPPJID jidWithString:jidStr];
        
        XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] userForJID:jid];
        
        TTTabItem* item = [[[TTTabItem alloc] initWithTitle:user.displayName] autorelease];
        item.object = jid;
        
        [self.tabDict setObject:item forKey:jidStr];
        
        
    }   
    self.tabBar.tabItems = [self.tabDict allValues];
    if (self.tabBar.tabItems.count >0) {
        self.jid = self.tabBar.selectedTabItem.object;
    }

    
}


#pragma mark - NSFetchedResultsControllerDelegate
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    if(controller ==_unreadController){
        
        
        switch(type) {
            case NSFetchedResultsChangeInsert: {
                Message* message= anObject;

                
                if (self.tabDict.count > 0){
                    [self updateTab:message.jidStr selected:NO];
                    
                }else{
                    [self setJid:[XMPPJID jidWithString: message.jidStr]];
                    
                }
                
                
                
                break;
            }
            case NSFetchedResultsChangeDelete: {
                
                break;
            }
        }
    }
    [self updateBadge];
    
}


- (void)handleMessageReceived:(NSNotification *)notification
{
    //[self updateBadge];
}

- (void)handleChatSwitch:(NSNotification *)notification
{
    
    XMPPUserCoreDataStorageObject* user=[notification object];
    self.jid=user.jid;
}



- (void)setJid:(XMPPJID *)jid
{
    [_jid release];
    _jid= [jid retain];
    
    if (jid!=nil) {
        NSString* jidStr=[jid bare];
        self.toolbar.hidden=NO;
        if (self.chatViewController == nil) {
            _chatViewController = [[ChatViewController alloc] initWithJidStr:jidStr];
            self.chatViewController.view.frame = CGRectMake(0, 85, self.view.width, self.view.height-85);
            [self.view addSubview:self.chatViewController.view];
        }else{
            self.chatViewController.view.hidden = NO;
            self.chatViewController.jidStr=jidStr;
        }
        
        [self updateTab:jidStr selected:YES];
        [self reloadAvatar];
    }else{
        self.toolbar.hidden=YES;
        self.chatViewController.view.hidden = YES;
        //self.chatViewController = nil;
        
    }
}

- (void)updateTab:(NSString*)jidStr selected:(BOOL)selected{
    TTTabItem* selectedItem= nil;
    if (self.tabBar.tabItems.count>0) {
        selectedItem= self.tabBar.selectedTabItem;
    }
    
    
    
    TTTabItem* item = [self.tabDict objectForKey:jidStr];
    
    if (item){
        //item.badgeNumber ++;
    }else{
        XMPPJID* jid = [XMPPJID jidWithString:jidStr];
        
        XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] userForJID:jid];
        
        item = [[[TTTabItem alloc] initWithTitle:user.displayName] autorelease];
        item.object = jid;
        
        [self.tabDict setObject:item forKey:jidStr];
        self.tabBar.tabItems = [self.tabDict allValues];
        //[self.tabBar layoutSubviews];
        
    }
    if (selected) {
        self.tabBar.selectedTabItem = item;
    }else{
        self.tabBar.selectedTabItem = selectedItem==nil?item:selectedItem;
    }
        
    //[self updateBadge];
    
    
    
}

- (void)updateBadge
{
    for (TTTabItem* item in self.tabBar.tabItems){
        item.badgeNumber = 0;
    }
    
    
    for (id <NSFetchedResultsSectionInfo> sectionInfo in [self.unreadController sections]) {
        TTTabItem* item =[ self.tabDict objectForKey:sectionInfo.name];
        if (item){
            item.badgeNumber = [[sectionInfo objects] count];
        }
        
    }
    
    NSInteger count = [[self.unreadController fetchedObjects] count];
    if (count >0){
        [UIApplication sharedApplication].applicationIconBadgeNumber = count;
        
    }else{
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }   
}


- (void)tabBar:(TTTabBar*)tabBar tabSelected:(NSInteger)selectedIndex
{
    TTTabItem* selected=[tabBar.tabItems objectAtIndex:selectedIndex];
    
    self.jid =selected.object;
    
}

- (void)closeAction:(id)sender;
{
    NSInteger index = self.tabBar.selectedTabIndex;
    
    [_tabDict removeObjectForKey:[_jid bare]];
    
    
    self.tabBar.tabItems = [self.tabDict allValues];
    
    if (self.tabBar.tabItems.count>0){
        self.tabBar.selectedTabIndex = MIN(index,self.tabBar.tabItems.count-1);
        if (self.tabBar.selectedTabItem){
            self.jid = self.tabBar.selectedTabItem.object;
        }
        else{
            self.jid = nil;
        }        
    }else{
        self.jid = nil;
    }
    
    
    
}

- (void)reloadAvatar{
    
    
    XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] userForJID:_jid];
    
    
    [self.titleView setAvatarImage: [[XMPPClient sharedInstance] avatarForJID:_jid]];
    
    NSString* name = user.displayName;
    
    if(!TTIsStringWithAnyText(name)){
        name = _jid.bare;
    }
    
    [self.titleView setName:name];
    
    XMPPResourceCoreDataStorageObject *resource =  user.primaryResource;
    
    if (resource){
        [self.titleView setStatus:resource.status];
        [self.titleView setIntShow:resource.intShow];
        
    }else{
        [self.titleView setOffline];
    }
    
}

- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    
    DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, presence);
    if (self.jid!=nil){
        if([presence.from isEqualToJID:_jid options:XMPPJIDCompareBare]){
            
            if (![@"unavailable" isEqualToString:presence.type] ){
                self.titleView.statusLabel.text = presence.status;
                [self.titleView setIntShow:presence.intShow];      
                
            }else{
                [self.titleView setOffline];
            }
            
            
        }
    }
    
	
}

@end
